package com.tianhao.luo.service.impl;

import com.tianhao.luo.config.Configuration;
import com.tianhao.luo.domain.entity.HfleFile;
import com.tianhao.luo.domain.entity.HiamUser;
import com.tianhao.luo.domain.mapper.HfleFileMapper;
import com.tianhao.luo.service.HfleFileService;
import com.tianhao.luo.thread.FileUploadThread;
import com.tianhao.luo.thread.FileUploadThreadBuilder;
import com.tianhao.luo.uitls.CommonException;
import com.tianhao.luo.uitls.FileClientBuilder;
import com.tianhao.luo.uitls.FileListUtil;
import com.tianhao.luo.uitls.FileOperator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName: HfleFileServiceImpl
 * @Description: 文件服务实现
 * @author: tianhao.luo@hand-china.com
 * @date: 2020/8/6  22:16
 */
@Service("HfleFileServiceImpl")
public class HfleFileServiceImpl implements HfleFileService {
    private static final Logger LOGGER = LoggerFactory.getLogger(HfleFileServiceImpl.class);
    @Autowired
    private HfleFileMapper hfleFileMapper;
    @Autowired
    private FileClientBuilder fileClientBuilder;

    @Autowired
    private Configuration configuration;
    @Autowired
    private FileUploadThreadBuilder fileUploadThreadBuilder;


    private ThreadPoolExecutor tpe = new ThreadPoolExecutor(2, 4, 10, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(2), new ThreadPoolExecutor.DiscardPolicy());


    @Override
    public HfleFile save(HiamUser hiamUser, MultipartFile file) {
        FileUploadThread fut = fileUploadThreadBuilder.build(hiamUser, file);
        Future<List<HfleFile>> submit = tpe.submit(fut);
        try {
            return submit.get().get(0);
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            return null;
        }
    }

    @Override
    public void downLoadFile(HfleFile hfleFile, HttpServletResponse httpServletResponse) {
        //获取文件上传客户端
        FileOperator<HfleFile,HiamUser> fileClient = fileClientBuilder.builder().init();
        fileClient.downLoadFile(hfleFileMapper.selectLimitOne(hfleFile),httpServletResponse);
    }

    @Override
    public List<HfleFile> batchSaveFile(HiamUser hiamUser, List<MultipartFile> files) throws Exception {
        if (CollectionUtils.isEmpty(files)){
            throw new CommonException("不能上传为空的文件","files_not_null");
        }else {
            int spiltNumber = Integer.parseInt(configuration.getServletRequest().getFile().getSpilt());
            if (files.size() > spiltNumber){
                LOGGER.info("待上传文件数量多，正在批量上传中！");
                List<HfleFile> hfleFiles = new ArrayList<>();
                List<List<MultipartFile>> filelistList = FileListUtil.spilt(spiltNumber, files);
                for (List<MultipartFile> multipartFiles : filelistList) {
                    FileUploadThread fileUploadThread = fileUploadThreadBuilder.build(hiamUser, multipartFiles);
                    Future<List<HfleFile>> submit = tpe.submit(fileUploadThread);
                    hfleFiles.addAll(submit.get());
                }
                LOGGER.info("文件上传完毕！");
                return hfleFiles;

            }else {
                FileUploadThread fileUploadThread = fileUploadThreadBuilder.build(hiamUser, files);
                Future<List<HfleFile>> submit = tpe.submit(fileUploadThread);
                return new ArrayList<>(submit.get());
            }
        }
    }
}
